package com.netty.service;

import com.alibaba.fastjson.JSON;
import com.netty.constant.Constants;
import com.netty.model.Message;
import com.netty.model.MessageBody;
import com.netty.model.MessageWrapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 茉莉机器人回复
 *
 * @author suzhen
 * @create 2018/7/16
 */
@Setter
@Slf4j
@Service
public class MoLiRobotServiceImpl implements RobotService {

    /**
     * 机器人apiurl
     */
    private String apiUrl;
    /**
     * 秘钥    请自行申请机器人KEY
     */
    private String key = "";
    private String secret = "";

    @Override
    public MessageWrapper botMessageReply(String user, String content) {
        log.info("MLRebot reply user -->" + user + "--mes:" + content);
        String message = "";
        try {
            //只实现了基础的  具体的请自行修改
            Document doc = Jsoup.connect(apiUrl).timeout(62000).data("api_key", key).data("api_secret", secret).data("limit", "5").data("question", content).post();
            message = doc.select("body").html();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Message result = new Message();
        result.setCmd(Constants.CmdType.MESSAGE);
        result.setType(Constants.ProtobufType.REPLY);
        //机器人ID
        result.setSender(Constants.ImserverConfig.REBOT_SESSIONID);
        //回复人
        result.setReceiver(user);
        result.setTimeStamp(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        MessageBody messageBody = new MessageBody();
        messageBody.setContent(message);
        result.setContent(JSON.toJSONString(messageBody));
        return new MessageWrapper(MessageWrapper.MessageProtocol.REPLY, Constants.ImserverConfig.REBOT_SESSIONID, user, result);
    }
}
